<template>
  <div>
    <el-dialog
      :visible="settingsVisible"
      :title="myIndex > -1? settingMode==='code'?'编辑': ''+titleName: '新增'+titleName"
      class="customClass"
      @close="closeDialog">
      <!-- {{ settingMode }} -->
      <!-- 新增环节 -->
      <el-form v-if="settingMode === 'code'" ref="code" :rules="rule" :model="settingForm" style="margin-left:20px">
        <el-form-item :label-width="labeWidth" label="溯源商品" prop="traceabilityGoodsId">
          <el-col :span="24" >
            <el-input :disabled="true" v-model="settingForm.goodName" style="width:50%" maxlength="100" />
            <el-input :disabled="true" v-model="settingForm.traceabilityGoodsId" style="width:60%; display:none;" class="goods" maxlength="100" />
            <el-button type="primary" size="small" class="ml20" plain @click="chooseLine()">请选择</el-button>
          </el-col>
        </el-form-item>
        <el-form-item :label-width="labeWidth" label="规则编号" prop="ruleNumber">
          <el-col :span="19" >
            <el-input :disabled="true" v-model="settingForm.ruleNumber" type="input" maxlength="200"/>
          </el-col>
        </el-form-item>
        <el-form-item :label-width="labeWidth" label="编码规则" prop="codingRules">
          <el-col :span="19" >
            <el-input :disabled="true" v-model="settingForm.codingRules" type="input" maxlength="200"/>
          </el-col>
        </el-form-item>
        <el-form-item :label-width="labeWidth" label="编码类型" prop="codingType">
          <el-col :span="19" >
            <!-- <el-input v-model="settingForm.codingType" type="input" maxlength="200"/> -->
            <el-select v-model="settingForm.codingType">
              <el-option :value="0" label="普通类型"/>
              <!-- <el-option :value="1" label="一般类型"/> -->
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item :label-width="labeWidth" label="说明" prop="description">
          <el-col :span="19" >
            <el-input v-model="settingForm.description" type="textarea" maxlength="200"/>
          </el-col>
        </el-form-item>
        <div class="bottomBtn">
          <el-button v-preventReClick type="primary" @click="submitForm('code')">确定</el-button>
          <el-button v-preventReClick type="info" @click="closeDialog">取消</el-button>
        </div>
      </el-form>

      <!-- // 新增标码 -->
      <el-form
        v-loading="createLoading"
        v-if="settingMode === 'createCode'"
        ref="createCode"
        :rules="rule"
        :model="createForm"
        element-loading-text="正在下载"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.8)"
        style="margin-left:20px">
        <el-form-item :label-width="labeWidth" label="生成数量" prop="number">
          <el-col :span="20" >
            <el-input v-model="createForm.number" class="input" placeholder="最多1000张" maxlength="100" />
          </el-col>
        </el-form-item>
        <div class="bottomBtn">
          <el-button v-preventReClick type="primary" @click="submitForm('createCode')">生成</el-button>
          <!-- <el-button v-preventReClick :loading="createLoading" type="primary" @click="submitForm('createCode')">生成</el-button> -->
          <el-button v-preventReClick type="info" @click="closeDialog">取消</el-button>
        </div>
      </el-form>

      <!-- 新增、编辑批次 -->
      <!-- {{ batchForm }} -->
      <el-form
        v-loading="createLoading"
        v-if="settingMode === 'createBatch'"
        ref="createBatch"
        :rules="rule"
        :model="batchForm"
        element-loading-text="正在下载"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.8)"
        style="margin-left:20px">
        <!-- <el-form-item :label-width="labeWidth" label="生成数量" prop="number">
          <el-col :span="20" >
            <el-input v-model="batchForm.number" class="input" placeholder="最多1000张" maxlength="100" />
          </el-col>
        </el-form-item> -->
        <!-- {{ batchForm }} -->
        <el-form-item :label-width="labeWidth" label="选择商品" prop="goods">
          <el-col :span="24" >
            <el-input :disabled="true" v-model="batchForm.goodName" style="width:50%" maxlength="100" />
            <el-input :disabled="true" v-model="batchForm.traceabilityGoodsId" style="width:60%; display:none;" class="goods" maxlength="100" />
            <el-button type="primary" size="small" class="ml20" plain @click="chooseSourceGoods()">请选择</el-button>
          </el-col>
        </el-form-item>
        <el-form-item :label-width="labeWidth" label="说明" prop="description">
          <el-col :span="19" >
            <el-input v-model="batchForm.description" type="textarea" maxlength="200"/>
          </el-col>
        </el-form-item>
        <div class="bottomBtn">
          <el-button v-preventReClick type="primary" @click="submitForm('createBatch')">确定</el-button>
          <!-- <el-button v-preventReClick :loading="createLoading" type="primary" @click="submitForm('createBatch')">生成</el-button> -->
          <el-button v-preventReClick type="info" @click="closeDialog">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 新增标码规则 -->
    <sourceGoods
      :choose-visible.sync="chooseVisible"
      :receive-data.sync="receiveData"
      @onReceiveData="receiveDataFn"/>

    <sourceGoods
      :choose-visible.sync="sourceGoodsVisible"
      :receive-data.sync="receiveData"
      @onReceiveData="receiveDataFn"/>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import carouselList from '@/components/carousel/list'
import { getCodingRules, createCode } from '@/api/source'
import config from '@/utils/config';
import axios from 'axios'
import sourceGoods from '@/components/sourceGoods'
// <sendGoods :send-goods-visible.sync="sendGoods" :send-goods-index="sendGoodsIndex" :send-goods-id="sendGoodsId"/>
export default {
  components: { carouselList, sourceGoods },
  props: {
    settingsVisible: {
      type: Boolean,
      required: true
    },
    myIndex: {
      type: Number,
      required: true
    },
    dialogData: {
      type: Object,
      required: true
    },
    settingMode: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      labeWidth: '80px',
      goodTypesForm: {},
      settingForm: {
        traceabilityGoodsId: '',
        goodName: '',
        ruleNumber: '',
        codingRules: '',
        codingType: 0,
        description: ''
      },
      createForm: {
        number: '',
        id: ''
      },
      tinymceDis: false,
      discountList: [],
      receiveData: {},
      chooseVisible: false,
      createLoading: false,
      downLoadUrl: config.baseUrl + '/code/generateCode',
      // 新增溯源批次
      batchForm: {
        traceabilityGoodsId: '',
        goodName: '',
        description: ''
      },
      sourceGoodsVisible: false,
      rule: {
        traceabilityGoodsId: [
          { required: true, message: '请选择溯源商品', trigger: 'blur' }
        ],
        ruleNumber: [
          { required: true, message: '请填规则编号', trigger: 'blur' }
        ],
        codingRules: [
          { required: true, message: '请填编码规则', trigger: 'blur' }
        ],
        codingType: [
          { required: true, message: '请填编码规则', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请填写生成数量', trigger: 'blur' },
          { pattern: /^([1-9]\d{0,2}|1000)$/, message: '请输入正整数，数字不能大于1000', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    titleName() {
      console.log(this.settingMode)
      const titleMap = {
        'code': '标码规则',
        'createCode': '生成标码',
        'createBatch': '商品批次'
      }
      return titleMap[this.settingMode]
    }
  },
  watch: {
    myIndex(val) {
      if (val > -1) {
        if (this.settingMode === 'code') this.settingForm = Object.assign({}, this.dialogData)
        if (this.settingMode === 'createCode') {
          this.createForm.id = this.dialogData.id
        }
        if (this.settingMode === 'createBatch') {
          console.log('dialogData:', this.dialogData)
          this.batchForm = Object.assign({}, this.dialogData)
        }
      } else {
        if (this.settingMode === 'code') this.settingForm = {}
      }
    }
  },
  mounted() {
    // if (this.settingMode === 'discount' || this.settingMode === 'membersRebate') {
    //   // this.getConstantPercent()
    //   this.getMomList()
    // }
  },
  methods: {
    // 生成二维码
    exportZip() {
      axios({
        method: 'get',
        url: config.BaseUrl + '/code/generateCode',
        params: this.createForm,
        responseType: 'blob'
      }).then((res) => {
        console.log('res::', res.request.responseURL)
        const blob = new Blob([res.data], { type: 'application/zip' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        console.log('url:::', [res.data])
        link.href = res.request.responseURL
        // link.download = '清单文件' // 重命名文件
        link.click()
      }).catch(err => {
        this.$Message.error(err)
      })
    },
    getCodingRulesFN() {
      getCodingRules().then(res => {
        console.log('编码规则：', res)
        this.settingForm.codingRules = res
      })
    },
    receiveDataFn(val) {
      // 生成标码 或者 标码规则

      if (this.settingMode === 'code') {
        console.log('传递回来的数据：', val)
        this.settingForm.traceabilityGoodsId = val.id
        this.settingForm.goodName = val.goodName
        let firstName = ''
        if (val.categoryName === '农产品') {
          firstName = 'NCP'
        } else if (val.categoryName === '贴剂') {
          firstName = 'TJ'
        } else {
          firstName = 'QT'
        }
        this.settingForm.ruleNumber = firstName + new Date().getTime()
        this.getCodingRulesFN() // 填写编码规则
      }

      if (this.settingMode === 'createCode') {
        console.log('传递回来的数据：', val)
        this.settingForm.traceabilityGoodsId = val.id
        this.settingForm.goodName = val.name
        this.settingForm.ruleNumber = val.name + new Date().getTime()
        this.getCodingRulesFN() // 填写编码规则
      }

      if (this.settingMode === 'createBatch') {
        console.log(val)
        this.batchForm.traceabilityGoodsId = val.id
        this.batchForm.goodName = val.goodName
        // this.batchForm.ruleNumber = val.name + new Date().getTime()
      }
    },
    chooseSourceGoods() {
      this.sourceGoodsVisible = true
    },
    chooseLine() {
      this.chooseVisible = true
    },
    submitForm(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          // 向父级插件冒一个‘updataParent’ 的方法, 并且把填好的数据带过去， 到父级去做处理
          console.log(this.settingForm)
          if (this.settingMode === 'code') {
            this.$emit('updataParent', this.settingForm)
            this.closeDialog()
            this.settingForm = {}
          }

          if (this.settingMode === 'createCode') {
            this.createLoading = true
            this.exportZip()
            // this.closeDialog()
            setTimeout(() => {
              this.createLoading = false
              Message.success('下载成功')
              // this.$emit('updataParent', this.createForm)
              this.closeDialog()
              this.createForm = {}
            }, 2000)
          }

          if (this.settingMode === 'createBatch') {
            this.$emit('updataParent', this.batchForm)
            this.closeDialog()
            this.batchForm = {}
          }
        }
      })
    },
    closeDialog() {
      this.$emit('update:settingsVisible', false)
      this.$emit('update:myIndex', -1)
      this.batchForm = {}
    }
  }
}
</script>
<style scoped>
.bottomBtn{
    height: 80px;
    padding-top: 20px;
    width:100%;
    text-align: center;
    border-top: 1px solid #ddd
}
.bottomBtn button{
    display: inline-block;
}
select{
    width:100%
}
.customClass .el-dialog{
    min-width: 400px;
    width: 400px;
    /* width: 60%; */
}
.el-input{
    width:100%
}
</style>
